package com.zhu.wechat.util;

import cn.hutool.extra.qrcode.QrCodeUtil;
import jakarta.servlet.http.HttpServletResponse;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.alibaba.fastjson.JSON;

import java.io.IOException;

@Component
public class WechatConfigUtil {
    // 要发送消息的应用的两个字段
    private static Integer agentId;
    private static String secret;
    // 企业id
    private static String corpId;

    @Value("${wx-cp-config.secret}")
    public void setSecret(String secret) {
        WechatConfigUtil.secret = secret;
    }

    @Value("${wx-cp-config.corpid}")
    public void setCorpId(String corpId) {
        WechatConfigUtil.corpId = corpId;
    }

    @Value("${wx-cp-config.agentid}")
    public void setAgentId(Integer agentId) {
        WechatConfigUtil.agentId = agentId;
    }

    /**
     * 配置企业微信服务
     *
     * @return
     */
    public static WxCpService getWxCpService() {
        WxCpService wxCpService = new WxCpServiceImpl();
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setAgentId(agentId);
        config.setCorpSecret(secret);
        config.setCorpId(corpId);
        resetTokenAndJsApi(wxCpService, config);
        return wxCpService;
    }

    /**
     * 重置token
     *
     * @param wxCpService
     * @param wxCpDefaultConfig
     */
    public static void resetTokenAndJsApi(WxCpService wxCpService, WxCpDefaultConfigImpl wxCpDefaultConfig) {
        Jedis jedis = new JedisPool().getResource();
        wxCpService.setWxCpConfigStorage(wxCpDefaultConfig);
        String wxAccessToken = "wx" + agentId;
        String json = jedis.get(wxAccessToken);  // 根据应用id获取对应token
        if (!StringUtils.isEmpty(json)) {
            wxCpDefaultConfig = JSON.parseObject(json, WxCpDefaultConfigImpl.class);
        }
        if (wxCpDefaultConfig.isAccessTokenExpired()) {  // token到期
            try {
                String accessToken = null;
                accessToken = wxCpService.getAccessToken(false);
                wxCpDefaultConfig.setAccessToken(accessToken);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        jedis.set(wxAccessToken, JSON.toJSONString(wxCpDefaultConfig));  // 缓存token
        jedis.close();
    }

//    public static String wxLogin(HttpServletResponse response) throws IOException {
//        String redirectUrl = "";
//        String url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE&agentid=AGENTID#wechat_redirect";
//        QrCodeUtil.generate(url1, 200, 200, "jpg", response.getOutputStream());
//        CloseableHttpClient client = HttpClients.createDefault();
//        HttpGet httpGet = new HttpGet(url1);
//        HttpResponse response1 = client.execute(httpGet);
//        JSONObject jsonObject = new JSONObject(response1.toString());
//        return jsonObject.getString("code");
//        //
//    }
//
}
